var windowWidth = -1;
var windowHeight = -1;
var BOTTOM_MARGIN = 32;
var RIGHT_MARGIN = 32;
var zoomed = false;
var unzoomedWidth;

var mOldPos;
var mOldTop;
var mOldLeft;
var mOldWidth;
var mOldHeight;

function toggleZoom() {
  var e = el('map3d');
  if (!zoomed) {
    mOldPos = e.style.position;
    mOldTop = e.style.top;
    mOldLeft = e.style.left;
    mOldWidth = e.style.width;
    mOldHeight = e.style.height;
    e.style.position = 'absolute';
    e.style.top = '0';
    e.style.left = '0';
    var winSize = windowSize();
    e.style.width = winSize[0] + "px";
    e.style.height = winSize[1] + "px";
    zoomed = true;
    setTimeout('showZoomHelp()', 500);
  } else {
    e.style.position = mOldPos;
    e.style.width = mOldWidth;
    e.style.height = mOldHeight;
    e.style.top = mOldTop;
    e.style.left = mOldLeft;
    zoomed = false;
  }
}

var logShown = false;
function toggleLog() {
  var e = el('log');
  if (!logShown) {
    e.style.zIndex = 10;
  } else {
    e.style.zIndex = -10;
  }
  logShown = !logShown;
}

function showZoomHelp() {
  alert('Hit the "Esc" key to exit zoom.');
}

function windowSize () {
  if (parseInt(navigator.appVersion)>3) {
    if (navigator.appName=="Netscape") {
      return [window.innerWidth, window.innerHeight];
    }
    if (navigator.appName.indexOf("Microsoft")!=-1) {
      return [document.body.offsetWidth, document.body.offsetHeight];
    }
  }
}

function getPosition(object) {
  var left = object.offsetLeft;
  var top = object.offsetTop;
  object = object.offsetParent;
  while (object) {    
    left += object.offsetLeft;
    top += object.offsetTop;
    object = object.offsetParent;
  }
  return [left, top];
}

function stretchToBottom(object) {
  var position = getPosition(object);
  var height = object.offsetHeight;
  var newHeight = windowHeight - position[1] - BOTTOM_MARGIN;
  if (newHeight > 0) {
    object.style.height = newHeight + 'px';
  }
}

function stretchToRight(object) {
  var position = getPosition(object);
  var newWidth = windowWidth - position[0] - RIGHT_MARGIN;
  if (newWidth > 0) {
    object.style.width = newWidth + 'px';
  }
}

var initResize = true;
var origW;
var origH;
function resize() {
  if (initResize) {
    var cont = el('map3d_container');
    origW = el.offsetWidth;
    origH = el.offsetHeight;
    initResize = false;
  }
  /**
   * Safari and IE respect specifying map3d elts with 100% height
   * inside an elt with computed height.  It's apparently a matter of
   * religious war whether this is to spec or not, but I like it, so
   * for now FF receives my ire. */
  if (navigator.userAgent.indexOf("Firefox") != -1) {
    var cont = el('map3d_container');
    var map3d = el('map3d');
    map3d.style.position = 'relative';
    map3d.style.top = '22px';
    map3d.style.width = (cont.clientWidth - 10) + 'px';
    map3d.style.height = (cont.clientHeight - 10) + 'px';
  }
}
